<template>
  <view class="order-list">
    <!-- 顶部分类选择 -->
    <!-- <uv-sticky offset-top="0" custom-nav-height="0"> -->
      <view class="order-tabs">
        <view 
        v-for="item in tabList" 
        :key="item.type"
        class="tab-item"
        :class="{ active: currentType === item.type }"
        @click="switchTab(item.type)"
      >
        {{ item.name }}
        </view>
      </view>
    <!-- </uv-sticky> -->
    
    <!-- 订单列表 -->
    <scroll-view 
      class="order-content" 
      scroll-y="true"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      style="height: calc(100vh - 100rpx);"
    >
      <view 
        class="order-item" 
        v-for="item in orderList" 
        :key="item.orderId"
      >
        <view class="order-header">
          <text class="order-no">id：{{ item.orderId }}</text>
          <!-- <text class="order-status" :class="getStatusClass(item.paymentStatus)">
            {{ getStatusText(item.paymentStatus) }}
          </text> -->
        </view>
        
        <view class="order-info">
          <text class="course-name">{{ item.courseName }}</text>
          <view class="info-left">
            <view class="countdown" v-if="item.paymentStatus === 0">
              <text class="countdown-label">结束时间：</text>
              <text class="countdown-time" :class="{'countdown-warning': countdowns[item.orderId]?.isNearTimeout}">
                {{ countdowns[item.orderId]?.text || '计算中...' }}
              </text>
            </view>
            <view class="detail-item">
              <text class="label">创建时间：{{ parseTime(item.orderDate) }}</text>
            </view>
            <view class="detail-item" v-if="item.payDate">
              <text class="label">支付时间：{{ parseTime(item.payDate) }}</text>
            </view>
          </view>
        </view>
        
        <!-- 订单操作按钮 -->
        <view class="order-actions">
          <!-- {{item.paymentStatus}} -->
          <template v-if="item.paymentStatus === 0 && !isTimeout(item.timeOut)">
            <button class="btn-cancel" @click="cancelOrder(item)">取消订单</button>
            <button class="btn-pay" @click="payOrder(item)">立即支付</button>
          </template>
          <template v-else-if="item.paymentStatus === 0 && isTimeout(item.timeOut)">
            <text class="timeout-text">订单已超时</text>
          </template>
          <!-- <template v-else-if="item.paymentStatus === 1">
            <button class="btn-detail" @click="refund(item)">申请退款</button>
          </template> -->
          <button class="btn-detail" @click="viewDetail(item,'theory')">练习理论</button>
          <button class="btn-detail" @click="viewDetail(item,'practice')">练习实操</button>

        </view>
      </view>
      
      <!-- 加载更多状态 -->
      <view class="load-more" v-if="orderList.length > 0">
        <text v-if="hasMore">上拉加载更多</text>
        <text v-else>没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="orderList.length === 0">
        <text>暂无订单数据</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getOrderList, cancelOrder } from '@/http/order.js'
import { parseTime } from '@/utils/tools.js'

export default {
  data() {
    return {
      currentType: null, // 当前选中的类型
      tabList: [
        { type: null, name: '全部' },
        // { type: '0', name: '未支付' },
        // { type: '1', name: '已支付' },
        // { type: '2', name: '已取消' }
      ],
      orderList: [],
      pageNum: 1,
      pageSize: 10,
      countdowns: {}, // 存储每个订单的倒计时状态
      timer: null,
      isRefreshing: false,
      hasMore: true,
      total: 0
    }
  },
  
  onLoad(options) {
    this.currentType = options.type || null
    this.getOrderList()
  },
  
  methods: {
    parseTime,
    
    // 切换标签
    switchTab(type) {
      this.currentType = type
      this.pageNum = 1
      this.orderList = []
      this.getOrderList()
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      this.pageNum = 1
      this.orderList = []
      await this.getOrderList()
      this.isRefreshing = false
    },
    
    // 上拉加载更多
    async onLoadMore() {
      if (!this.hasMore) return
      this.pageNum++
      await this.getOrderList(true)
    },
    
    // 获取订单列表
    async getOrderList(isLoadMore = false) {
      if (!isLoadMore) {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
      }
      
      try {
        const res = await getOrderList({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          status: this.currentType
        })
        // 处理数据
        if (isLoadMore) {
          this.orderList = [...this.orderList, ...res.data.list]
        } else {
          this.orderList = res.data.list
        }
        uni.hideLoading()
        // 更新分页信息
        this.total = res.data.total
        this.hasMore = this.orderList.length < this.total
        
        // 只有当订单列表有数据时才启动倒计时
        if (this.orderList && this.orderList.length > 0) {
          this.startCountdown()
        }
      } catch(err) {
        uni.showToast({
          title: err.message || '加载失败',
          icon: 'none'
        })
      } finally {
        if (!isLoadMore) {
          uni.hideLoading()
        }
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        4: '已退款',
        5: '退款申请中'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        0: 'status-pending',
        1: 'status-paid',
        2: 'status-cancelled',
        4: 'status-refunded',
        5: 'status-refunding'
      }
      return classMap[status] || ''
    },
    
    // 支付订单
    payOrder(item) {
      console.log(item);
      uni.navigateTo({
        url: `/pages/order/info?orderId=${item.orderId}?id=${item.courseId}`
      })
    },
    
    // 取消订单
    cancelOrder(item) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await cancelOrder({
                orderId: item.orderId
              })
              uni.showToast({
                title: '取消成功',
                icon: 'none'
              })
              this.pageNum = 1
              this.orderList = []
              this.getOrderList()
            } catch(err) {
              uni.showToast({
                title: err.message || '取消失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 查看详情
    viewDetail(item,type) {
      if(type == 'theory'){
        uni.switchTab({
          url: `/pages/index/index`
        })
      }else{
        uni.switchTab({
          url: `/pages/practicalTest/practicalTest`
        })
      }
    },
    
    // 检查订单是否超时
    isTimeout(timeOut) {
      return new Date().getTime() > timeOut
    },
    
    // 更新所有倒计时
    updateCountdowns() {
      const now = new Date().getTime()
      
      this.orderList.forEach(item => {
        if (item.paymentStatus === 0) {
          const diff = item.timeOut - now
          
          if (diff <= 0) {
            this.countdowns[item.orderId] = {
              text: '已超时',
              isNearTimeout: true
            }
            item.paymentStatus = 2
          } else {
            const minutes = Math.floor(diff / 1000 / 60)
            const seconds = Math.floor((diff / 1000) % 60)
            
            this.countdowns[item.orderId] = {
              text: `${minutes}分${seconds < 10 ? '0' : ''}${seconds}秒`,
              isNearTimeout: minutes < 5
            }
          }
        }
      })
      
      this.$forceUpdate()
    },
    
    // 启动倒计时
    startCountdown() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      
      const hasUnpaidOrders = this.orderList.some(item => item.paymentStatus === 0)
      
      if (!hasUnpaidOrders) {
        return
      }
      
      this.updateCountdowns()
      
      this.timer = setInterval(() => {
        this.updateCountdowns()
      }, 1000)
    }
  },
  
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  
  onHide() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  
  onShow() {
    if (this.orderList && this.orderList.length > 0) {
      this.startCountdown()
    }
  }
}
</script>

<style lang="scss" scoped>
.order-list {
  min-height: 100vh;
  background: #f7f7f7;
  
  .order-tabs {
    display: flex;
    background: #fff;
    padding: 20rpx 0;
    position: sticky;
    top: 0;
    z-index: 1;
    
    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #333;
      position: relative;
      padding: 20rpx 0;
      
      &.active {
        color: #FD3523;
        font-weight: bold;
        
        &:after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60rpx;
          height: 4rpx;
          background: #FD3523;
          border-radius: 2rpx;
        }
      }
    }
  }
  
  .order-content {
    flex: 1;
    box-sizing: border-box;
    padding-bottom: env(safe-area-inset-bottom);
    
    .order-item {
      background: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin: 20rpx;
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .order-no {
          font-size: 26rpx;
          color: #999;
        }
        
        .order-status {
          font-size: 28rpx;
          font-weight: bold;
          
          &.status-pending { color: #FF9900; }
          &.status-paid { color: #52C41A; }
          &.status-cancelled { color: #999; }
          &.status-refunded { color: #666; }
          &.status-refunding { color: #40a9ff; }
        }
      }
      
      .order-info {
        padding: 20rpx 0;
        border-bottom: 1rpx solid #eee;
        
        .course-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 15rpx;
          display: block;
        }
        
        .info-left {
          .countdown {
            display: flex;
            align-items: center;
            margin-top: 10rpx;
            
            .countdown-label {
              font-size: 24rpx;
              color: #666;
            }
            
            .countdown-time {
              font-size: 24rpx;
              color: #333;
              font-weight: bold;
              
              &.countdown-warning {
                color: #ff4d4f;
              }
            }
          }
          
          .detail-item {
            margin-top: 10rpx;
            
            .label {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
      
      .order-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 30rpx;
        
        button {
          margin-left: 20rpx;
          min-width: 160rpx;
          height: 60rpx;
          line-height: 60rpx;
          font-size: 26rpx;
          border-radius: 30rpx;
          
          &.btn-cancel {
            color: #666;
            background: #f5f5f5;
          }
          
          &.btn-pay {
            color: #fff;
            background: #FD3523;
          }
          
          &.btn-detail {
            color: #FD3523;
            background: #fff;
            border: 1rpx solid #FD3523;
          }
        }
      }
    }
    
    .load-more {
      text-align: center;
      padding: 20rpx 0;
      color: #999;
      font-size: 24rpx;
    }
    
    .empty-state {
      text-align: center;
      padding: 100rpx 0;
      color: #999;
      font-size: 28rpx;
    }
  }
}

.timeout-text {
  color: #999;
  font-size: 26rpx;
}
</style>